var tabNums=0;//记录tab展开的数量
var tabnames="";//记录现打开tab的标题名（多个中间用逗号隔开）
var adminrole=null;
$(function() {
	// 取消Ajax的缓存
	$.ajaxSetup({
		cache : false,
		Complete: function (x, status, error) {
            if (x.status == 403) {
                alert("Sorry, your session has expired. Please login again to continue");
                window.location.href ="/403.jsp";
            }
            else {
                alert("An error occurred: " + status + "nError: " + error);
            }
        }
    });
	
	
	
	$("#tabs").tabs({
		onClose:function(title){
			tabNums--;
		},onAdd:function(title){
			tabNums++;
		}
		});
	showusermenu();
	
/*	$.ajax({
		type : "GET",
		url : "/admin/getMyTaskNum",
		dataType : "json",
		// traditional: true,
		success : function(result) {
			$("tasknum").attr("value",result.tasknum);
		}
	});*/
	
	//alert($("div").children(".selected"));
	/*$.get("/admin/getMyTaskNum",
			 function(result) {
		$("#tasknum").attr("value",result.tasknum);
	});*/
/*	$("#tabs").tabs("getTab", "首页")({
		onLoad:function(title,index){
			alert('页面被加载');
		}
	});*/
	addTab("首页", '/rbac/adminindex.jsp')
});


/*关闭所有的tab*/
function closealltabs(){
	$(function () {
        $.messager.confirm("操作提示", "您确定要关闭所有标签页吗？", function (data) {
            if (data) {
            	if (""!=tabnames){
          	      var childtabs=tabnames.split(",");
          	      var len=childtabs.length;
          	      var n=0;
          	      for (;n<len;n++){
          	    	  closeTab(childtabs[n]);
          	      }
          	      tabnames="";
          	    }
            }
        });
    });
}

//以iframe的方式打开网页
function createFrame(url) {
	var s = '<iframe name="auto" scrolling="auto" frameborder="0" src="'+ url + '" style="width:100%;height:100%;"></iframe>';
	return s;
}

//根据标题关闭指定tab
function closeTab(subtitle) {
		if ($("#tabs").tabs("exists", subtitle)) {
			$("#tabs").tabs("close", subtitle);
		} 
}
	
//新增tab，参数：标题，地址
function addTab(subtitle, url) {
    purl=url;
    ptitle=subtitle;
	if(tabNums<10){
		if ($("#tabs").tabs("exists", subtitle)) {
			//$("#tabs").tabs("close", subtitle);
			$("#tabs").tabs("select", subtitle);
			var currTab =  self.parent.$('#tabs').tabs('getSelected'); //获得当前tab
		    var url = $(currTab.panel('options').content).attr('src');
		    self.parent.$('#tabs').tabs('update', {
		      tab : currTab,
		      options : {
		       content : createFrame(url),
		       selected:true
		      }
		     });

		}else{
			$("#tabs").tabs("add", {
				title : subtitle,
				content : createFrame(url),
				closable : true
			});	
			if (""==tabnames){
		    	tabnames=subtitle;
		    }else{
		    	tabnames+=","+subtitle;
		    }
		} 
		
		
	}else{
		alert("为保证系统性能，最多只能打开10个标签页！");
	}
}

function zTreeOnClick(event,treeId,treeNode){
	//alert(treeNode.name);
	if (null!=treeNode.path){
		if (""!=treeNode.path){
			addTab(treeNode.name,path+treeNode.path);
			return;
		}
	}
		var zTree = $.fn.zTree.getZTreeObj("usermenus");
		zTree.expandNode(treeNode, null, null, null, true);
};

/***
 * 显示刷新所有菜单树
 */
 function showusermenu() {
	 //alert(adminrole);
	
	function onExpand(event, treeId, treeNode) {
		curExpandNode = treeNode;
	};
	var setting = {
			view : {
				showIcon : true
			},
			edit : {
				enable : false,
				showRemoveBtn : false,
				showRenameBtn : false
			},
			data : {
				keep : {
					parent : true
				},
				key : {
					name : "name"
				},
				simpleData : {
					enable : true,
					idKey : "id",
					pIdKey : "pid"
				}
			},
			async : {
				enable : true,
				cache : true,
				url : "/rbac/getResourceByRoleidForUser",
				//autoParam:["id"]

				//autoParam: ["roleid", adminrole],
				//otherParam : [ "roleid", adminrole ],
				otherParam : ["roleid", adminrole, "type", 'menu' ]
			},
			callback : {
				onClick: zTreeOnClick
			}
		};
		var t = $("#usermenus");
		t = $.fn.zTree.init(t, setting, []);
	}
 
 //修改密码
 function showChangePass(){
	 openpersonnelDialog('修改密码');
	 
 }
 $.extend($.fn.validatebox.defaults.rules, {
	    equals: {
			validator: function(value,param){
				return value == $(param[0]).val();
			},
			message: '您输入的密码，不一致，请重新输入'
	    }
	});

 
 function openpersonnelDialog(title) {
		//clearCachePersonnelDialog();
	 $(':input')
	 .not(':button, :submit, :reset, :hidden')
	 .val('')
	 .removeAttr('checked')
	 .removeAttr('selected');
	
		$('#changePassDialog').dialog({
			title : title,
			width : 260,
			height : 200,
			closed : false,
			cache : false,
			modal : true,
			buttons : [ {
				text : '保存',
				handler : function() {
					
						changePass();
					
				}
			}, {
				text : '关闭',
				handler : function() {
					$('#changePassDialog').window('close');
				}
			} ]
		});
	}
 
 function changePass(){
	 if($("#changePassForm").form('validate'))  {
	 //alert('保存密码');
		 $.ajax( {    
			    url:'/rbac/changePassWord',// 跳转到 action    
			    data:{    
			    	oldpass : $("#oldpass").val(),   
			    	newpass : $("#rpwd").val()    
			               
			    },    
			    type:'post',    
			    cache:false,    
			    dataType:'json',    
			    success:function(data) {    
			        if(data.msg =="ok" ){    
			            // view("修改成功！");  
			        	$.messager.alert('success','修改成功','success');
			        	$('#changePassDialog').window('close');
			             
			        }else{    
			        	$.messager.alert('error',data.msg,'error');    
			        }    
			     },    
			     error : function() {    
			          // view("异常！");    
			          alert("异常！");    
			     }    
			});  
 }
 else{
	 alert("输入错误");
 }
 }
 
 
